package com.swak.generate.codegen.dialects;

import java.util.List;

import com.swak.generate.codegen.Table;
import com.swak.generate.codegen.TableColumn;
import com.swak.utils.StringUtils;

/**
 * H2 的代码生成工具
 * 
 * @author lifeng
 * @date 2020年9月21日 上午10:06:21
 */
public class H2Operater extends AbstractOperater {

	private final String FETCH_TABLES_SQL = "SELECT T.TABLE_NAME AS NAME, T.REMARKS AS COMMENTS FROM INFORMATION_SCHEMA.`TABLES` T WHERE T.TABLE_CATALOG = (SELECT DATABASE()) AND T.TABLE_SCHEMA='PUBLIC'";
	private final String FETCH_TABLE_COLUMNS_SQL = """
			  SELECT T.COLUMN_NAME AS NAME,
			         (CASE WHEN T.ORDINAL_POSITION = 1 THEN '1' ELSE '0' END) AS IS_PK,
			      (CASE WHEN T.IS_NULLABLE = 'YES' THEN '1' ELSE '0' END) AS IS_DB_NULL,
			   T.ORDINAL_POSITION AS SORT, '' AS COMMENTS, T.DATA_TYPE AS DB_TYPE,
			   (CASE WHEN T.CHARACTER_MAXIMUM_LENGTH IS NULL THEN T.NUMERIC_PRECISION ELSE T.CHARACTER_MAXIMUM_LENGTH END) NUMERIC_PRECISION,
			   T.NUMERIC_SCALE FROM INFORMATION_SCHEMA.COLUMNS T
			WHERE T.TABLE_CATALOG = (SELECT DATABASE())
			  AND T.TABLE_NAME = UPPER('%s') ORDER BY T.ORDINAL_POSITION
			""";

	public H2Operater(String url, String userName, String passWord) {
		super(url, userName, passWord);
	}

	@Override
	public List<String> getTables() {
		return this.execSql(FETCH_TABLES_SQL, (rs, sn) -> {
			return rs.getString("NAME");
		});
	}

	@Override
	public Table getTable(String table) {
		List<TableColumn> columns = this.execSql(StringUtils.format(FETCH_TABLE_COLUMNS_SQL, table), (rs, sn) -> {
			TableColumn column = new TableColumn();
			column.setName(rs.getString("NAME"));
			column.setDbType(rs.getString("DB_TYPE"));
			column.setIsNull((byte) rs.getInt("IS_DB_NULL"));
			column.setIsPk((byte) rs.getInt("IS_PK"));
			column.setComments(rs.getString("COMMENTS"));
			return column;
		});
		Table _table = new Table();
		_table.setName(StringUtils.upperCase(table));
		_table.setColumns(columns);
		return _table;
	}
}